﻿// -------------------------------------------------------------------------------------------------------
// LICENSE INFORMATION
//
// - This software is licensed under the MIT shared source license.
// - The "official" source code for this project is maintained at http://mtcagent.codeplex.com
//
// Copyright (c) 2010 OpenNETCF Consulting
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
// associated documentation files (the "Software"), to deal in the Software without restriction, 
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial 
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
// -------------------------------------------------------------------------------------------------------

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using OpenNETCF.Web;
using System.Diagnostics;
using OpenNETCF.IoC;
using System.Xml.Linq;
using System.Threading;

namespace OpenNETCF.MTConnect
{
    public partial class VirtualAgentHandler : MTConnectHandlerBase
    {
        private IHostedAdapterService m_svc;

        public string VirtualAgentRoot = "/agent";

        [EventPublication(EventNames.RestartRequested)]
        public event EventHandler RestartRequested;

        [EventPublication(EventNames.StatusUpdate)]
        public event EventHandler<GenericEventArgs<StatusSummary>> StatusUpdate;

        public VirtualAgentHandler()
        {
            // register ourself so we can publish events
            RootWorkItem.Services.Add<VirtualAgentHandler>(this);
        }

        internal IHostedAdapterService HostedAdapterService
        {
            get
            {
                if (m_svc == null)
                {
                    m_svc = RootWorkItem.Services.Get<IHostedAdapterService>();
                }
                return m_svc;
            }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            var et = Environment.TickCount;

            string message = string.Format("{0} at {1}",
                context.Request.HttpMethod,
                context.Request.Path);

            StatusUpdate.Fire(this, new GenericEventArgs<StatusSummary>(
                new StatusSummary()
                {
                    Source = context.Request.UserHostAddress,
                    Description = message,
                    TimeStamp = DateTime.Now
                }
                ));

            switch (context.Request.RequestType.ToUpper())
            {
                case "GET":
                    HandleGet(context);
                    break;
                case "PUT":
                    HandlePut(context);
                    break;
                case "POST":
                    HandlePost(context);
                    break;
            }

            et = Environment.TickCount - et;

            Debug.WriteLineIf((et > 100), string.Format("VirtualAgentHandler took {0}ms at {1}", et, context.Request.Path));
        }

        private string GetRequestData(HttpContext context)
        {
            var buffer = new byte[context.Request.InputStream.Length];
            context.Request.InputStream.Read(buffer, 0, buffer.Length);
            return Encoding.UTF8.GetString(buffer);
        }

        private string[] GetRequestPathSegments(HttpContext context)
        {
            var path = context.Request.Url.PathAndQuery;
            // strip out the agent root
            var index = path.IndexOf(VirtualAgentRoot, StringComparison.InvariantCultureIgnoreCase);

            if (index < 0)
            {
                throw new HttpException(HttpErrorCode.MethodNotAllowed, "Unsupported POST");
            }

            path = path.Substring(index + VirtualAgentRoot.Length);

            var segments = (from s in path.Split('/')
                            where !string.IsNullOrEmpty(s)
                            select s).ToArray();

            return segments;
        }
    }
}
